#!/bin/bash

# 定义变量
MASTER_IP="192.168.2.138"
NODE1_IP="192.168.2.139"
HOSTNAME="k8s-master"
NODE1_HOSTNAME="k8s-node1"
SSH_USER="root"

# 设置脚本在发生错误时停止执行
set -e

# 输出日志函数
log() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - INFO - $1"
}

# 错误处理函数
error() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - ERROR - $1"
    exit 1
}

# 更新 /etc/hosts 文件
log "Updating /etc/hosts file..."
# 检查是否已经存在记录，如果不存在则添加
if ! grep -q "$MASTER_IP $HOSTNAME" /etc/hosts; then
    echo "$MASTER_IP $HOSTNAME" | sudo tee -a /etc/hosts > /dev/null
fi
if ! grep -q "$NODE1_IP $NODE1_HOSTNAME" /etc/hosts; then
    echo "$NODE1_IP $NODE1_HOSTNAME" | sudo tee -a /etc/hosts > /dev/null
fi
log "/etc/hosts file updated successfully."

# 设置主机名
log "Setting hostname to $NODE1_HOSTNAME..."
sudo hostnamectl set-hostname $NODE1_HOSTNAME
if [ $? -ne 0 ]; then
    error "Failed to set hostname."
fi
log "Hostname set to $NODE1_HOSTNAME successfully."

# 创建并配置 /etc/sysctl.d/k8s.conf 文件
log "Creating and configuring /etc/sysctl.d/k8s.conf file..."
cat > /etc/sysctl.d/k8s.conf <<EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
vm.swappiness = 0
EOF
if [ $? -ne 0 ]; then
    error "Failed to create or configure /etc/sysctl.d/k8s.conf file."
fi
log "/etc/sysctl.d/k8s.conf file configured successfully."

# 加载 br_netfilter 模块
log "Loading br_netfilter module..."
sudo modprobe br_netfilter
if [ $? -ne 0 ]; then
    error "Failed to load br_netfilter module."
fi
log "br_netfilter module loaded successfully."

# 查看是否加载 br_netfilter 模块
log "Checking if br_netfilter module is loaded..."
if ! lsmod | grep -q br_netfilter; then
    error "br_netfilter module is not loaded."
fi
log "br_netfilter module is loaded successfully."

# 加载网桥过滤及内核转发配置文件
log "Loading bridge filter and kernel forwarding configuration file..."
sudo sysctl -p /etc/sysctl.d/k8s.conf
if [ $? -ne 0 ]; then
    error "Failed to load bridge filter and kernel forwarding configuration file."
fi
log "Bridge filter and kernel forwarding configuration file loaded successfully."

log "All tasks completed successfully."

# 备份 CentOS-Base.repo 文件
log "Backing up CentOS-Base.repo file..."
sudo mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak
if [ $? -ne 0 ]; then
    error "Failed to back up CentOS-Base.repo file."
fi
log "CentOS-Base.repo file backed up successfully."

# 下载新的 CentOS-Base.repo 文件
log "Downloading new CentOS-Base.repo file..."
sudo curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
if [ $? -ne 0 ]; then
    error "Failed to download new CentOS-Base.repo file. Please check the URL and your network connection."
fi
log "New CentOS-Base.repo file downloaded successfully."

# 清理 YUM 缓存并重建缓存
log "Cleaning YUM cache and rebuilding cache..."
sudo yum clean all
if [ $? -ne 0 ]; then
    error "Failed to clean YUM cache."
fi
sudo yum makecache
if [ $? -ne 0 ]; then
    error "Failed to rebuild YUM cache."
fi
log "YUM cache cleaned and rebuilt successfully."

log "All tasks completed successfully."

# 同步时间使用 chrony
log "Synchronizing time with chrony..."

# 安装 chrony
log "Installing chrony..."
sudo yum install -y chrony
if [ $? -ne 0 ]; then
    error "Failed to install chrony."
fi
log "Chrony installed successfully."

# 配置 chrony 使用阿里云的 NTP 服务器
log "Configuring chrony to use ntp.aliyun.com..."
sudo sed -i 's/^#\(server.*iburst\)/\1/' /etc/chrony.conf
sudo sed -i '/^server.*iburst/a server ntp.aliyun.com iburst' /etc/chrony.conf
if [ $? -ne 0 ]; then
    error "Failed to configure chrony."
fi
log "Chrony configured successfully."

# 启动并启用 chrony 服务
log "Starting and enabling chrony service..."
sudo systemctl start chronyd
sudo systemctl enable chronyd
if [ $? -ne 0 ]; then
    error "Failed to start or enable chrony service."
fi
log "Chrony service started and enabled successfully."

# 立即同步时间
log "Synchronizing time immediately..."
sudo chronyc -a makestep
if [ $? -ne 0 ]; then
    error "Time synchronization failed."
fi
log "Time synchronized successfully."

# 安装 ipset 和 ipvsadm
log "Installing ipset and ipvsadm..."
sudo yum -y install ipset ipvsadm
if [ $? -ne 0 ]; then
    error "Failed to install ipset and ipvsadm."
fi
log "ipset and ipvsadm installed successfully."

# 创建并编辑 /etc/sysconfig/modules/ipvs.modules 文件
log "Creating and editing /etc/sysconfig/modules/ipvs.modules file..."
cat > /etc/sysconfig/modules/ipvs.modules <<EOF
#!/bin/bash
modprobe -- ip_vs
modprobe -- ip_vs_rr
modprobe -- ip_vs_wrr
modprobe -- ip_vs_sh
modprobe -- nf_conntrack
EOF
if [ $? -ne 0 ]; then
    error "Failed to create or edit /etc/sysconfig/modules/ipvs.modules file."
fi
log "/etc/sysconfig/modules/ipvs.modules file created and edited successfully."

# 给予执行权限
log "Granting execute permissions to /etc/sysconfig/modules/ipvs.modules..."
sudo chmod 755 /etc/sysconfig/modules/ipvs.modules
if [ $? -ne 0 ]; then
    error "Failed to grant execute permissions to /etc/sysconfig/modules/ipvs.modules."
fi
log "Execute permissions granted to /etc/sysconfig/modules/ipvs.modules successfully."

# 运行模块脚本
log "Running the modules script..."
sudo bash /etc/sysconfig/modules/ipvs.modules
if [ $? -ne 0 ]; then
    error "Failed to run the modules script."
fi
log "Modules script run successfully."

# 检验是否成功
log "Checking if modules are loaded successfully..."
if ! lsmod | grep -q -e ip_vs -e nf_conntrack; then
    error "Modules are not loaded successfully."
fi
log "Modules are loaded successfully."

log "All tasks completed successfully."

# 停止 firewalld 服务
log "Stopping firewalld service..."
sudo systemctl stop firewalld
if [ $? -ne 0 ]; then
    error "Failed to stop firewalld service."
fi
log "Firewalld service stopped successfully."

# 关闭 SELinux（如果未禁用）
log "Disabling SELinux..."
sudo setenforce 0
if [ $? -ne 0 ]; then
    error "Failed to disable SELinux."
fi
log "SELinux disabled successfully."

# 临时关闭 swap
log "Temporarily turning off swap..."
sudo swapoff -a
if [ $? -ne 0 ]; then
    error "Failed to temporarily turn off swap."
fi
log "Swap turned off temporarily successfully."

# 永久关闭 swap，注释掉 /etc/fstab 中的 swap 条目
log "Permanently turning off swap by commenting out the entry in /etc/fstab..."
sudo sed -i '/\/dev\/mapper\/centos-swap/s/^/#/' /etc/fstab
if [ $? -ne 0 ]; then
    error "Failed to comment out swap entry in /etc/fstab."
fi
log "Swap entry commented out in /etc/fstab successfully."

log "All tasks completed successfully."

# 下载 Docker 的 YUM 源配置文件
log "Downloading Docker YUM repository configuration file..."
sudo curl -o /etc/yum.repos.d/docker.repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
if [ $? -ne 0 ]; then
    error "Failed to download Docker YUM repository configuration file. Please check the URL and your network connection."
fi
log "Docker YUM repository configuration file downloaded successfully."

# 安装 Docker-CE
log "Installing Docker-CE..."
sudo yum -y install docker-ce
if [ $? -ne 0 ]; then
    error "Failed to install Docker-CE."
fi
log "Docker-CE installed successfully."

log "All tasks completed successfully."

# 创建 /etc/docker 目录
log "Creating /etc/docker directory..."
sudo mkdir -p /etc/docker
if [ $? -ne 0 ]; then
    error "Failed to create /etc/docker directory."
fi
log "/etc/docker directory created successfully."

# 配置 /etc/docker/daemon.json 文件
log "Configuring /etc/docker/daemon.json file..."
cat > /etc/docker/daemon.json <<EOF
{
    "registry-mirrors": ["https://docker.mirrors.ustc.edu.cn", "https://docker.m.daocloud.io", "http://hub-mirrors.c.163.com"],
    "max-concurrent-downloads": 10,
    "log-driver": "json-file",
    "log-level": "warn",
    "data-root": "/var/lib/docker"
}
EOF
if [ $? -ne 0 ]; then
    error "Failed to configure /etc/docker/daemon.json file."
fi
log "/etc/docker/daemon.json file configured successfully."

# 重启 Docker 服务
log "Restarting Docker service..."
sudo systemctl restart docker
if [ $? -ne 0 ]; then
    error "Failed to restart Docker service."
fi
log "Docker service restarted successfully."

log "All tasks completed successfully."

# 安装 wget 工具
log "Installing wget..."
sudo yum -y install wget
if [ $? -ne 0 ]; then
    error "Failed to install wget."
fi
log "wget installed successfully."

# 定义变量
DOWNLOAD_URL="https://github.com/Mirantis/cri-dockerd/releases/download/v0.3.4/cri-dockerd-0.3.4.amd64.tgz"
TGZ_FILE="cri-dockerd-0.3.4.amd64.tgz"
EXTRACT_DIR="cri-dockerd"

# 下载压缩包
log "Downloading the package..."
wget $DOWNLOAD_URL -O $TGZ_FILE
if [ $? -ne 0 ]; then
    error "Failed to download the package. Please check the URL and your network connection."
fi
log "Package downloaded successfully."

# 解压压缩包
log "Extracting the package..."
tar zxvf $TGZ_FILE
if [ $? -ne 0 ]; then
    error "Failed to extract the package."
fi
log "Package extracted successfully."

# 拷贝二进制命令文件到 /usr/bin/
log "Copying binary files to /usr/bin/..."
sudo cp $EXTRACT_DIR/* /usr/bin/
if [ $? -ne 0 ]; then
    error "Failed to copy binary files to /usr/bin/."
fi
log "Binary files copied to /usr/bin/ successfully."

log "All tasks completed successfully."

# 配置 cri-docker.service
log "Configuring cri-docker.service..."
cat > /usr/lib/systemd/system/cri-docker.service <<EOF
[Unit]
Description=CRI Interface for Docker Application Container Engine
Documentation=https://docs.mirantis.com
After=network-online.target firewalld.service docker.service
Wants=network-online.target
Requires=cri-docker.socket

[Service]
Type=notify
ExecStart=/usr/bin/cri-dockerd --network-plugin=cni --pod-infra-container-image=registry.aliyuncs.com/google_containers/pause:3.7
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutSec=0
RestartSec=2
Restart=always
StartLimitBurst=3
StartLimitInterval=60s
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity
Delegate=yes
KillMode=process

[Install]
WantedBy=multi-user.target
EOF
if [ $? -ne 0 ]; then
    error "Failed to configure cri-docker.service."
fi
log "cri-docker.service configured successfully."

# 配置 cri-docker.socket
log "Configuring cri-docker.socket..."
cat > /usr/lib/systemd/system/cri-docker.socket <<EOF
[Unit]
Description=CRI Docker Socket for the API
PartOf=cri-docker.service

[Socket]
ListenStream=%t/cri-dockerd.sock
SocketMode=0660
SocketUser=root
SocketGroup=docker

[Install]
WantedBy=sockets.target
EOF
if [ $? -ne 0 ]; then
    error "Failed to configure cri-docker.socket."
fi
log "cri-docker.socket configured successfully."

# 重新加载 systemd 配置并启用 cri-docker 服务
log "Reloading systemd daemon and enabling cri-docker service..."
sudo systemctl daemon-reload
sudo systemctl enable --now cri-docker
if [ $? -ne 0 ]; then
    error "Failed to reload systemd daemon or enable cri-docker service."
fi
log "systemd daemon reloaded and cri-docker service enabled successfully."

# 检查 cri-docker 服务状态
log "Checking status of cri-docker service..."
systemctl status cri-docker > /dev/null
if [ $? -ne 0 ]; then
    error "cri-docker service is not running."
fi
log "cri-docker service is running successfully."

# 添加 Kubernetes YUM 源
log "Adding Kubernetes YUM repository..."
cat > /etc/yum.repos.d/kubernetes.repo <<EOF
[kubernetes]
name=Kubernetes
baseurl=http://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg http://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
exclude=kubelet kubeadm kubectl
EOF
if [ $? -ne 0 ]; then
    error "Failed to add Kubernetes YUM repository."
fi
log "Kubernetes YUM repository added successfully."

# 安装 Kubernetes 组件
log "Installing Kubernetes components..."
sudo yum -y install kubelet-1.27.4-0 kubeadm-1.27.4-0 kubectl-1.27.4-0 --disableexcludes=kubernetes
if [ $? -ne 0 ]; then
    error "Failed to install Kubernetes components."
fi
log "Kubernetes components installed successfully."

# 设置 kubelet 开机自启
log "Enabling kubelet to start on boot..."
sudo systemctl enable --now kubelet
if [ $? -ne 0 ]; then
    error "Failed to enable kubelet to start on boot."
fi
log "kubelet enabled to start on boot successfully."

# 检查 kubelet 服务状态
log "Checking status of kubelet service..."
systemctl is-active kubelet > /dev/null
if [ $? -ne 0 ]; then
    error "kubelet service is not active."
fi
log "kubelet service is active."

log "All tasks completed successfully."

